//
//  SupplyChainViewController.m
//  Globalstone
//
//  Created by 刘建峰 on 16/7/4.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "SupplyChainViewController.h"
#import "SupplyChainTableViewCell.h"
#import "ExportOngoingViewController.h"

static NSString * cellIndentifier = @"SupplyChainTableViewCell";

@interface SupplyChainViewController ()<UITableViewDelegate,UITableViewDataSource>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;
@property (weak, nonatomic) IBOutlet UIView *navView;
@property (weak, nonatomic) IBOutlet UIView *typeView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *allIndentButton;
@property (weak, nonatomic) IBOutlet UIButton *underWayIndentButton;
@property (weak, nonatomic) IBOutlet UIButton *doneIndentButton;
@property (weak, nonatomic) IBOutlet UIButton *inIndentButton;
@property (weak, nonatomic) IBOutlet UIButton *outIndentButton;
@property(nonatomic,strong)NSMutableArray * indentsArray;
@end

@implementation SupplyChainViewController
- (void)viewWillAppear:(BOOL)animated{
    [self changeLanguage];
    if ([Common getLoginStatus]) {
        [self.tableView.header beginRefreshing];
    }
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNO = 1;
    [self initViewLayout];
    [self addRefreshing];
    _indentsArray = [NSMutableArray array];
    // Do any additional setup after loading the view.
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.typeView];
    self.view.backgroundColor = [UIColor colorWithWhite:0.941 alpha:1.000];
    _tableView.frame = CGRectMake(0, 104*VerticalRatio(), 320*VerticalRatio(), 464*VerticalRatio()-49);
    [_tableView registerNib:[UINib nibWithNibName:cellIndentifier bundle:nil] forCellReuseIdentifier:cellIndentifier];
    _tableView.dataSource = self;
    _tableView.delegate = self;
}

#pragma mark == 语言切换
- (void)changeLanguage{
    [_inIndentButton setTitle:InternationalControl(@"进口") forState:UIControlStateNormal];
    [_outIndentButton setTitle:InternationalControl(@"出口") forState:UIControlStateNormal];
    [_allIndentButton setTitle:InternationalControl(@"全部订单") forState:UIControlStateNormal];
    [_underWayIndentButton setTitle:InternationalControl(@"进行中") forState:UIControlStateNormal];
    [_doneIndentButton setTitle:InternationalControl(@"已完成") forState:UIControlStateNormal];
}


#pragma mark === 进出口切换
- (IBAction)inOrOut:(UIButton *)sender {
    sender.selected = YES;
    [_indentsArray removeAllObjects];
    if (sender==_inIndentButton) {
        _outIndentButton.selected = NO;
    }else{
        _inIndentButton.selected = NO;
    }
    [_tableView.header beginRefreshing];
}


#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if (![Common getLoginStatus]) {
            [[AppDelegate sharedAppDelegate]ShowLoginPage];
            [_indentsArray removeAllObjects];
            [_tableView reloadData];
            [self.tableView.header endRefreshing];
            return ;
        }else{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.tableView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            if (_inIndentButton.selected) {
                [self getOrderImportList];
            }else{
                [self getOrderExportList];
            }
        });
        }
    }];
    // 马上进入刷新状态
    [self.tableView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.indentsArray.count == _totle) {
        [self.tableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            if (_inIndentButton.selected) {
                [self getOrderImportList];
            }else{
                [self getOrderExportList];
            }
        });
    }
    
}


#pragma mark === 出口订单
- (void)getOrderExportList{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:[Common getLoginInfo][Key_User_userId] forKey:@"museId"];
   [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    [dic setObject:[NSNumber numberWithInteger:_pageNO] forKey:@"page"];
    [dic setObject:[NSNumber numberWithInteger:PageSize] forKey:@"pageSize"];
    NSString * lan = [InternationalControl userLanguage];
    if ([lan isEqualToString:@"en"]) {
        [dic setObject:@"2" forKey:@"language"];
    }else{
        [dic setObject:@"1" forKey:@"language"];
    }
    if (_allIndentButton.selected) {
          [dic setObject:@"" forKey:@"oexpStatus"];
    }else if (_underWayIndentButton.selected){
        [dic setObject:@"1" forKey:@"oexpStatus"];
    }else{
        [dic setObject:@"5" forKey:@"oexpStatus"];
    }
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:GS_queryOrderExportList withHttpType:@"POST" withTag:GS_GS_queryOrderExportList];
}

#pragma mark === 进口订单
- (void)getOrderImportList{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:[Common getLoginInfo][Key_User_userId] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    [dic setObject:[NSNumber numberWithInteger:_pageNO] forKey:@"page"];
    [dic setObject:[NSNumber numberWithInteger:PageSize] forKey:@"pageSize"];

    NSString * lan = [InternationalControl userLanguage];
    if ([lan isEqualToString:@"en"]) {
        [dic setObject:@"2" forKey:@"language"];
    }else{
        [dic setObject:@"1" forKey:@"language"];
    }
    if (_allIndentButton.selected) {
         [dic setObject:@"" forKey:@"oimpStatus"];
    }else if (_underWayIndentButton.selected){
        [dic setObject:@"1" forKey:@"oimpStatus"];
    }else{
        [dic setObject:@"8" forKey:@"oimpStatus"];
    }
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:GS_queryOrderImportList withHttpType:@"POST" withTag:GS_GS_queryOrderImportList];
}

#pragma mark == 切换订单状态
- (IBAction)changeTypes:(UIButton *)sender {
    sender.selected = YES;
    [_indentsArray removeAllObjects];

    if (sender == _allIndentButton) {
        _underWayIndentButton.selected = NO;
        _doneIndentButton.selected = NO;
    }else if (sender == _underWayIndentButton){
        _allIndentButton.selected = NO;
        _doneIndentButton.selected = NO;
    }else{
        _allIndentButton.selected = NO;
        _underWayIndentButton.selected = NO;

    }
    [_tableView.header beginRefreshing];


}


#pragma mark ==== UItableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _indentsArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 133*VerticalRatio();
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SupplyChainTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
    if (cell == nil) {
        cell = [[SupplyChainTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
    }
    NSDictionary * dic = _indentsArray[indexPath.row];
        cell.indentName.text = [NSString stringWithFormat:@"%@",dic[@"orderTypeName"]];
        cell.indentNumber.text =  [NSString stringWithFormat:@"%@",dic[@"orderSysId"]];
        cell.indentAddress.text =  [NSString stringWithFormat:@"%@",dic[@"orderStatusDesc"]];
    cell.indentNoLabel.text = [NSString stringWithFormat:@"%@",dic[@"orderSysId"]];
        NSString * image = [NSString stringWithFormat:@"%@",dic[@"orderImage"]];
        if (image.length>0) {
            [cell.indentImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
        }
    
    NSInteger status = [[NSString stringWithFormat:@"%@",dic[@"orderStatus"]]integerValue];
    NSString * cuStatus = @"";
    if (_inIndentButton.selected) {
         if (status<8){
            cuStatus = @"进行中";
        }else{
            cuStatus = @"已完成";
        }
    }else{
        if (status < 5){
            cuStatus = @"进行中";
        }else{
            cuStatus = @"已完成";
        }
    }
    cell.indentStatus.text = InternationalControl(cuStatus);

    
    cell.indentNum.text = InternationalControl(@"订单号:");
    cell.freightStatus.text = InternationalControl(@"货运状态:");
    cell.currentAddress.text = InternationalControl(@"货物当前地址:");
    
    [cell.freightStatus sizeToFit];
    [cell.currentAddress sizeToFit];
    
    cell.indentStatusInfo.frame = flexibleFrame(CGRectMake(CGRectGetMaxX(cell.freightStatus.frame)/VerticalRatio(), 81, 320-CGRectGetMaxX(cell.freightStatus.frame)/VerticalRatio(), 15), NO);
    cell.indentAddress.frame = flexibleFrame(CGRectMake(CGRectGetMaxX(cell.currentAddress.frame)/VerticalRatio(), 100, 320-CGRectGetMaxX(cell.currentAddress.frame)/VerticalRatio(), 15), NO);
    return  cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"SupplyChainStoryboard" bundle:nil];
    ExportOngoingViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"ExportOngoing"];
    
    NSDictionary * dic = _indentsArray[indexPath.row];
    page.indentId = [NSString stringWithFormat:@"%@",dic[@"orderId"]];
    page.indentNum = [NSString stringWithFormat:@"%@",dic[@"orderSysId"]];
    page.currentStatus = [[NSString stringWithFormat:@"%@",dic[@"orderStatus"]]integerValue];
    if (_inIndentButton.selected) {
        page.type = @"1";
    }else{
        page.type = @"2";
    }
    
    
    if (_allIndentButton.selected) {
        page.indentStatus = @"1";
    }else if (_underWayIndentButton.selected){
        page.indentStatus = @"2";
    }else{
        page.indentStatus = @"3";
    }
    
    [[Common getNavigation]pushViewController:page];
    
}



#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
    if (tag==GS_GS_queryOrderExportList||tag==GS_GS_queryOrderImportList) {
        
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            if ([database[@"result"] isEqual:[NSNull null]]) {
                return;
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"total"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.tableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.indentsArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"list"];
                for (id entity in arr) {
                    [self.indentsArray addObject:entity];
                }
           
                [_tableView reloadData];
                
            });
        }
    }
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
        [self dismissWaitDialog];
        
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
